<?php
/*******************************************************************************
 * Project: Bridge for WordPress to phpBB 3.0.x
 * File:    plugin.php
 * Author:  Jason Sanborn <jsanborn@simplicitypoint.com>
 * Date:    Saturday, July 11, 2009
 * -----------------------------------------------------------------------------
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

function wpb_init()
{
	if(wpb_is_active())
	{
		$session_id = wpb_load_session();
		wpb_check_redirect($session_id);
	}
}

function wpb_load_session()
{
	global $wpdb, $phpbb_root_path, $phpEx, $auth, $user, $db, $config, $cache, $template;

	if(!defined('IN_PHPBB'))
    {
        define('IN_PHPBB', true);
    }
	$phpbb_config = trim(get_option('wpb_path'));
	$phpbb_root_path = dirname($phpbb_config) . '/';
	$phpEx = substr(strrchr($phpbb_config, '.'), 1);

	require($phpbb_config);
	require($phpbb_root_path . 'includes/acm/acm_' . $acm_type . '.' . $phpEx);
	require($phpbb_root_path . 'includes/cache.' . $phpEx);
	require($phpbb_root_path . 'includes/template.' . $phpEx);
	require($phpbb_root_path . 'includes/session.' . $phpEx);
	require($phpbb_root_path . 'includes/auth.' . $phpEx);
	require($phpbb_root_path . 'includes/functions.' . $phpEx);
	require($phpbb_root_path . 'includes/constants.' . $phpEx);
	require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);

	$user = new user();
	$auth = new auth();
	$template = new template();
	$cache = new cache();
	$db = new $sql_db();

	$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, defined('PHPBB_DB_NEW_LINK') ? PHPBB_DB_NEW_LINK : false);
	unset($dbpasswd);
	$config = $cache->obtain_config();

	$user->session_begin();
	$auth->acl($user->data);
	$user->setup();
	$userid = wpb_get_userid();

	if($userid <= 0 && is_user_logged_in())
	{
		wp_logout();
		wp_redirect('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
	}
	else if($userid > 0 && $userid != $user->ID)
	{
		wp_set_current_user($userid);
		wp_set_auth_cookie($userid, true, false);
		wpb_update_user($userid, $user);
	}

	return $user->session_id;
}

function wpb_check_redirect($session_id)
{
    
	$filename = strtolower(basename($_SERVER['SCRIPT_FILENAME']));
	$redirect = trim($redirect_to);
    
	if(empty($redirect))
	{
		$redirect = get_option('home');
	}

	if($filename == "wp-login.php" && is_user_logged_in())
	{
		wp_redirect(get_option('wpb_url') . "?mode=logout&sid=" . $session_id);
	}
	else if($filename == "wp-login.php" && !is_user_logged_in())
	{
		wp_redirect(get_option('wpb_url') . "?mode=login&redirect=" . $redirect);
	}
	else if($filename == "wp-signup.php" && !is_user_logged_in())
	{
		wp_redirect(get_option('wpb_url') . "?mode=register");
	}
    
}

function wpb_get_userid()
{
	global $wpdb, $user;
	require_once(ABSPATH . WPINC . '/registration.php');
	$userid = 0;

	if($user->data['user_type'] == USER_NORMAL || $user->data['user_type'] == USER_FOUNDER)
	{
		$id_list = $wpdb->get_col($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'phpbb_userid' AND meta_value = %d", $user->data['user_id']));

		if(empty($id_list))
		{
			$check_email = email_exists($user->data['user_email']);

			if($user->data['user_id'] == 2)
			{
				$userid = 1;
			}
			else if($check_email)
			{
				$userid = $check_email;
			}
			else
			{
				$userid = wp_create_user(wpb_get_username(), wp_generate_password(), $user->data['user_email']);
			}

			update_usermeta($userid, 'phpbb_userid', $user->data['user_id']);
		}
		else
		{
			$userid = $id_list[0];
		}
	}

	return $userid;
}

function wpb_get_username($count = 0)
{
	global $user;
	
	$new_username = ereg_replace("[^A-Za-z0-9]", "", $user->data['username']);
	$new_username = strtolower($new_username);

	if($count > 0)
	{
		$new_username .= (string)$count;
	}

	if(username_exists($new_username))
	{
		$count++;
		$new_username = wpb_get_username($count);
	}

	return $new_username;
}

function wpb_update_user($userid)
{
	global $user;

	$userdata['ID'] = $userid;
	$userdata['user_url'] = $user->data['user_website'];
	$userdata['user_email'] = $user->data['user_email'];
	$userdata['nickname'] = $user->data['username'];
	$userdata['jabber'] = $user->data['user_jabber'];
	$userdata['aim'] = $user->data['user_aim'];
	$userdata['yim'] = $user->data['user_yim'];

	wp_update_user($userdata);
}

?>